/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Apr 14, 2012  5:01:04 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.fi.inbound
 * File Name : ReReceiptedService.java
 * TODO
 */
package sap.business.fi.inbound;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import jpa.entitys.synchro.common.ACTION_HANDLER;
import jpa.entitys.synchro.staging.FiReReceiptInb;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.FiReReceiptInbservices;
import org.apache.log4j.Logger;
import promis.utility.CommonService;
import sap.business.commons.services.CommonJCOReturn;
import apps.promis.in.sales.ReReceiptedAction;
import com.sap.mw.jco.JCO;

/**
 * 
 * @author Chatree Siangklom of Administrator
 * Date =Nov 26, 2013 : 9:58:31 AM 
 * CreateBy=Chatree Siangklom
 * 
 * ReReceiptedService
 * TODO
 */
public class ReReceiptedService {
	
	private static final Logger log = Logger.getLogger(ReReceiptedService.class);
	
	public void CreatedSync(JCO.ParameterList input, JCO.ParameterList tables, JCO.ParameterList output, String structureOrTableName) throws Exception {
		List<FiReReceiptInb> lst = null;
		EntityManager em = null;
		FiReReceiptInbservices FiReReceiptInbServ = null;
		List<FiReReceiptInb> lst_object = new ArrayList<FiReReceiptInb>();
		JCO.Table table = tables.getTable(structureOrTableName);
		int records = -1;
		try{
			
			em = new SessionEntityManager().CreatedEntityManager();
			FiReReceiptInbServ = new FiReReceiptInbservices(em);
			String instance_no = FiReReceiptInbServ.GetNewInstanceNo();
			
			records = table.getNumRows();
			for(int i = 0; i < records; i++)
			{
				//log.info("i ="+ i);
				table.setRow(i);			
				FiReReceiptInb model = new FiReReceiptInb();
				
				//model.setPromisStagingId(CommonService.IsNullRNull(table.getString("PROMIS_STAGING_ID")));
				model.setInstanceNo(instance_no);
				//model.setCompanyCode(CommonService.IsNullRNull(table.getString("COMPANY")));
				model.setSapCompanyCode(CommonService.IsNullRNull(table.getString("SAP_COMPANY_CODE")));
				model.setSapPlantCode(CommonService.IsNullRNull(table.getString("PLANT_CODE")));
				
				model.setReceiptDate(CommonService.IsNullRNull(table.getString("RECEIPT_DATE")));
				model.setStatus(CommonService.IsNullRNull(table.getString("STATUS")));
				model.setContractDocumentNo(CommonService.IsNullRNull(table.getString("CONTRACT_DOCUMENT_NO")));
				model.setBookingDocumentNo(CommonService.IsNullRNull(table.getString("BOOKING_DOCUMENT_NO")));
				model.setInterestReceived(CommonService.IsNullRNull(table.getString("INTEREST_RECEIVED")));
				model.setDiscount(CommonService.IsNullRNull(table.getString("DISCOUNT")));
				model.setCustomerCode(CommonService.IsNullRNull(table.getString("CUSTOMER_CODE")));
				model.setCustomerName(CommonService.IsNullRNull(table.getString("CUSTOMER_NAME")));
				model.setAmount(CommonService.IsNullRNull(table.getString("AMOUNT")));
				model.setVatAmount(CommonService.IsNullRNull(table.getString("VAT_AMOUNT")));
				model.setWhtAmount(CommonService.IsNullRNull(table.getString("WHT_AMOUNT")));
				
				//SAP Not Have 2012-08-23 Achiray, Naphacha, Wut
				//Dr.Tree
				//model.setRemarksH(CommonService.IsNullRNull(table.getString("REMARKS")));
				
				model.setPropertyTypeCode(CommonService.IsNullRNull(table.getString("PROPERTY_TYPE_CODE")));
				model.setBuildingPhaseCode(CommonService.IsNullRNull(table.getString("BUILDING_PHASE_CODE")));
				model.setFloorZoneCode(CommonService.IsNullRNull(table.getString("FLOOR_ZONE_CODE")));
				model.setUnitNumber(CommonService.IsNullRNull(table.getString("UNIT_NUMBER")));
				model.setAddressCustomer(CommonService.IsNullRNull(table.getString("ADDRESS_CUSTOMER")));
				model.setNetAmountReceived(CommonService.IsNullRNull(table.getString("NET_AMOUNT_RECEIVED")));
				
				model.setNarration(CommonService.IsNullRNull(table.getString("NARRATION")));
				model.setReceivedFrom(CommonService.IsNullRNull(table.getString("RECEIVED_FROM")));
				model.setRefDocument(CommonService.IsNullRNull(table.getString("REF_DOCUMENT")));
				model.setSeqNo(CommonService.IsNullRNull(table.getString("SEQ_NO")));
				model.setReceivedType(CommonService.IsNullRNull(table.getString("RECEIVED_TYPE")));
				model.setChequeNumber(CommonService.IsNullRNull(table.getString("CHEQUE_NUMBER")));
				model.setBankCode(CommonService.IsNullRNull(table.getString("BANK_CODE")));
				model.setChequeDueDate(CommonService.IsNullRNull(table.getString("CHEQUE_DUE_DATE")));
				model.setChequeAmount(CommonService.IsNullRNull(table.getString("CHEQUE_AMOUNT")));
				model.setRemarksD(CommonService.IsNullRNull(table.getString("REMARKS")));
				model.setChequeIssuingBank(CommonService.IsNullRNull(table.getString("CHEQUE_ISSUING_BANK")));
				
				model.setBankCharge(CommonService.IsNullRNull(table.getString("BANK_CHARGE")));
				model.setBankDate(CommonService.IsNullRNull(table.getString("BANK_DATE")));
				model.setPayinDate(CommonService.IsNullRNull(table.getString("PAYIN_DATE")));
				model.setBranch(CommonService.IsNullRNull(table.getString("BRANCH")));
				model.setBankCardReader(CommonService.IsNullRNull(table.getString("BANK_CARD_READER")));
				model.setCreditCardType(CommonService.IsNullRNull(table.getString("CREDIT_CARD_TYPE")));
				
				//BANK_CHARGE is sane BANK_CHARGE1 
				//Dr.Tree 2012-08-23
				//model.setBankCharge1(CommonService.IsNullRNull(table.getString("BANK_CHARGE1")));
				model.setBankCharge1(CommonService.IsNullRNull(table.getString("BANK_CHARGE")));
				
				model.setRefDocument(CommonService.IsNullRNull(table.getString("REF_DOCUMENT")));
				model.setPaymentType(CommonService.IsNullRNull(table.getString("PAYMENT_TYPE")));
				model.setInstallmentNumber(CommonService.IsNullRNull(table.getString("INSTALLMENT_NUMBER")));
				model.setInstallmentSeq(CommonService.IsNullRNull(table.getString("INSTALLMENT_SEQ")));
				model.setAmountReceived(CommonService.IsNullRNull(table.getString("AMOUNT_RECEIVED")));
				model.setPaymentSeq(CommonService.IsNullRNull(table.getString("PAYMENT_SEQ")));				
				model.setInstallmentDueAmount(CommonService.IsNullRNull(table.getString("INSTALL_DUE_AMT")));
				
				//ChequePdcRef 
				//Add On 2013-03-01
				//DR.TREE
				model.setChequePdcRef(CommonService.IsNullRNull(table.getString("CHEQUE_REF")));
				
				
				//Comment out 2012-08-23
				//Dr.Tree, Wut SAP, Arthi SAP
				//model.setBankChageRate(CommonService.IsNullRNull(table.getString("BANK_CHARGE_RATE")));
				
				//Set Txn Reacord
				model.setCreatedOn(CommonService.IsNullRNull(table.getString("CREATED_ON")));
				model.setCreatedBy(CommonService.IsNullRNull(table.getString("CREATED_BY")));
				model.setUpdatedOn(CommonService.IsNullRNull(table.getString("LAST_UPD_ON")));
				model.setUpdatedBy(CommonService.IsNullRNull(table.getString("LAST_UPD_BY")));
				
				if(CommonService.IsNull(table.getString("LAST_UPD_ON")))
					model.setActionHandler(ACTION_HANDLER.INSERTED.toString());
				else 
					model.setActionHandler(ACTION_HANDLER.UPDATED.toString());
				
				//Set SAP External Key link
				model.setExtRefKey(CommonService.IsNullRNull(table.getString("SYNC_EXTERNAL_REF_KEY")));
				model.setExtRefNo(CommonService.IsNullRNull(table.getString("SYNC_EXTERNAL_REF_NO")));
				
				model.setInterfaceNo("FI-T2-020");
			
				log.info(model.toString());
				lst_object.add(model);
			}
			
			//Create To Staging
			FiReReceiptInbServ.Inserted(lst_object);
			log.info("Create to Staging  ---> ");
			
			//find By Instance No 
			lst = FiReReceiptInbServ.findByInstanceNo(instance_no);
			log.info("find By Instance No : "+ instance_no +" ---> ");			
			
			if(!CommonService.IsNull(lst))
			{
				//Validate Field
				boolean ispass = new ReReceiptedAction().ValidatedAndSave(lst);
				
				//Find By Instanceno
				lst = FiReReceiptInbServ.findByInstanceNo(instance_no);
				if(ispass){
					//Create To Promis
					new ReReceiptedAction().Processing(lst);
				}
				
				if(CommonService.getSize(lst) == records){
					for(int i = 0; i < records; i++)
					{
						FiReReceiptInb obj = lst.get(i);
						table.setRow(i);
						table.setValue(CommonService.IsNullRString(obj.getPromisStagingId()), "PROMIS_TXN_ID");
						table.setValue(CommonService.IsNullRString(obj.getMsgCode()), "MSG_CODE");
						table.setValue(CommonService.IsNullRString(obj.getMsgDesc()), "MSG_DESC");
						table.setValue(CommonService.IsNullRString(obj.getMsgAltDesc()), "MSG_ALT_DESC");
						table.setValue(CommonService.IsNullRString(obj.getMsgActResult()), "MSG_ACTION_RESULT");
						log.info(CommonJCOReturn.toString(table));
					}
				}
				
			}else
				log.info("Data not found  instance no = " + instance_no);
		}
		catch(Exception e)
		{	
			System.err.println(e.getMessage());
			log.error(e.getMessage());			
			
			if(!CommonService.IsNull(lst)){
				List<FiReReceiptInb> lstnew = new ArrayList<FiReReceiptInb>();
				for(FiReReceiptInb model : lst){
					model.setIssync("Y");
					model.setMsgCode("E");
					model.setMsgDesc(CommonService.CutString(e.getMessage(), 3500));
					model.setMsgAltDesc("ExtRefNo:" + model.getExtRefNo() + "|| ExtRefKey:" + model.getExtRefKey());
					model.setMsgActResult(CommonService.CutString(e.getMessage(), 3500));
					lstnew.add(model);
				}
				new FiReReceiptInbservices(em).Updated(lstnew);
				
				//******************************************************
				if(CommonService.getSize(lstnew) == records){
					for(int i = 0; i < records; i++)
					{
						FiReReceiptInb obj = lstnew.get(i);
						table.setRow(i);
						table.setValue(CommonService.IsNullRString(obj.getPromisStagingId()), "PROMIS_TXN_ID");
						table.setValue("E", "MSG_CODE");
						table.setValue(e.getMessage(), "MSG_DESC");
						table.setValue("ExtRefNo:"+obj.getExtRefNo() + "||ExtRefKey:" + obj.getExtRefKey(), "MSG_ALT_DESC");
						table.setValue("", "MSG_ACTION_RESULT");
						
						try {
							log.info(CommonJCOReturn.toString(table));
						} catch (Exception e1) {
							System.err.println(e1.getMessage());
							log.error(e1.getMessage());							
						}
					}
				}
			}else{		
				for(int i = 0; i < records; i++)
				{
					table.setRow(i);
					table.setValue("E", "MSG_CODE");
					table.setValue(e.getMessage(), "MSG_DESC");
				}
			}
		}
	}
}
